package com.zx.oa.controller;

import com.zx.oa.entity.ClassInfo;
import com.zx.oa.entity.Major;
import com.zx.oa.entity.Result;
import com.zx.oa.service.ClassInfo.ClassInfoServiceImpl;
import com.zx.oa.service.admin.AdminServiceIpml;
import com.zx.oa.service.major.MajorService;
import com.zx.oa.service.major.MajorServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/login.do","/logon.do"})
public class LoginServlet extends HttpServlet{

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if ("/login.do".equals(request.getServletPath())){
            doLogin(request,response);
        }else if("/logon.do".equals(request.getServletPath())){
            doLogon(request,response);
        }

        

    }

    private void doLogon(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            //销毁session
            session.invalidate();
            //回到登录页面
            response.sendRedirect(request.getContextPath());
        }
    }

    private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        //获取所有专业名称和所有班级名称。存到session中给展示
        MajorService major = new MajorServiceImpl();
        List<Major> majors = major.getMajorAll();
        //班级信息
        ClassInfoServiceImpl classInfoService = new ClassInfoServiceImpl();
        List<ClassInfo> classInfo = classInfoService.getClassInfo(null);
        List<Result> results = new ArrayList<>();
        results.add(new Result("差"));
        results.add(new Result("中等"));
        results.add(new Result("好"));
        results.add(new Result("非常好"));


        AdminServiceIpml adminServiceIpml = new AdminServiceIpml();

        if(adminServiceIpml.login(name, pwd)) {
            HttpSession session= request.getSession();
            //专业信息
            session.setAttribute("majors",majors);
            //班级信息
            session.setAttribute("classes",classInfo);
            //成绩
            session.setAttribute("results",results);
            //登录用户
            session.setAttribute("loginName",name);
            response.sendRedirect(request.getContextPath()+"/jsp/main.jsp");
        }else{
            response.sendRedirect("login.jsp");
        }
    }
}
